<template>
    <div class="material-add">
        <a-modal width="1200px" :visible="visible" :title="modalOption.title" @ok="modalOption.onOk"
            @cancel="modalOption.onCancel" :okText="modalOption.okText" :cancelText="modalOption.cancelText"
            class="yuan-modal material-add-modal">
            <a-spin tip="Loading..." :spinning="formLoading">
                <a-form-model layout="inline" class="yuan-form" ref="form" :model="formData" :rules="rules"
                    :label-col="{ style: { width: '100px' } }" :wrapper-col="{ style: { width: 'calc(100% - 120px)' } }">
                    <div class="form-panel">
                        <div class="form-panel-box">

                            <a-form-model-item class="yuan-form-item" label="物料类型" prop="productType">
                                <a-radio-group v-model="formData.productType"
                                    :options="tabsData.map(item=>({label:item.name,value:item.name}))" disabled />
                            </a-form-model-item>

                            <template v-if="formData.productType==='中药材'">
                                <!-- <a-form-model-item class="yuan-form-item" label="药材类别" prop="medicinalCategory">
                                    <a-radio-group v-model="formData.medicinalCategory">
                                        <a-radio value="植物药">植物药</a-radio>
                                        <a-radio value="动物药">动物药</a-radio>
                                        <a-radio value="矿物药">矿物药</a-radio>
                                    </a-radio-group>
                                </a-form-model-item> -->
                                <a-form-model-item class="yuan-form-item" label="来源" prop="source">
                                    <a-radio-group v-model="formData.source">
                                        <a-radio value="自培育">自培育</a-radio>
                                        <a-radio value="野生">野生</a-radio>
                                        <a-radio value="动物类">动物类</a-radio>
                                        <a-radio value="矿物类">矿物类</a-radio>
                                        <a-radio value="特殊类">特殊类</a-radio>
                                    </a-radio-group>
                                </a-form-model-item>

                                <!-- <a-form-model-item class="yuan-form-item" :label="infoId?'重新选择':'选择基原'" prop="1">
                                    <a-select class="yuan-form-input" v-model="formData.subjectId" placeholder="请选择科目" show-search
                                        :filter-option="$filterOption" @change="subjectChange" style="margin-right:5px">
                                        <a-select-option :value="item.id" v-for="(item,idx) in subjectList"
                                            :key="'ke_'+idx">{{item.typename}}</a-select-option>
                                    </a-select>
                                    <a-select class="yuan-form-input" v-model="formData.categoryIdx" placeholder="请选择属"
                                        show-search :filter-option="$filterOption" @change="categoryChange"
                                        style="margin-right:5px">
                                        <template v-if="categoryList && categoryList.length>0">
                                            <a-select-option :value="idx" v-for="(item,idx) in categoryList"
                                                :key="'su_'+idx">{{item}}</a-select-option>
                                        </template>
                                        <a-select-option value="0" disabled v-else>请先选择科目</a-select-option>

                                    </a-select>
                                    <a-select class="yuan-form-input" v-model="formData.seedIdx" placeholder="请选择种" show-search
                                        :filter-option="$filterOption" @change="seedChange">

                                        <template v-if="seedList && seedList.length>0">
                                            <a-select-option :value="idx" v-for="(item,idx) in seedList"
                                                :key="'zh_'+idx">{{item.seedName}}</a-select-option>
                                        </template>
                                        <a-select-option value="0" disabled v-else>请先选择属</a-select-option>
                                    </a-select>
                                </a-form-model-item> -->

                                <a-form-model-item class="yuan-form-item" label="基原信息" prop="1">
                                    <span style="margin-right:15px">科：{{formData.subjectName || '--'}}</span>
                                    <span style="margin-right:15px">属：{{formData.genericName || '--'}}</span>
                                    <span style="margin-right:15px">种：{{formData.basinymName || '--'}}</span>
                                    <span>拉丁文名：{{formData.basinymLatin || '--'}}</span>
                                </a-form-model-item>

                            </template>
                            <a-form-model-item v-if="formData.productType === '中药饮片'" class="yuan-form-item yuan-form-col3" label="中药等级" prop="medicineClass">
                                <a-radio-group v-model="formData.medicineClass" class="yuan-form-input" @change="medicineClassChange">
                                    <a-radio value="统货">统货</a-radio>
                                    <a-radio value="选货">选货</a-radio>
                                </a-radio-group>
                            </a-form-model-item>
                            <div class="clear-both"></div>
                            <a-form-model-item class="yuan-form-item yuan-form-col3" label="品种" prop="varietyName">
                                <a-input class="yuan-form-input" v-model="formData.varietyName" placeholder="请输入"
                                    @input="varietyNameChange"></a-input>
                            </a-form-model-item>
                            <a-form-model-item v-if="formData.productType==='直服饮片'" class="yuan-form-item yuan-form-col3" label="包装形式" prop="usageAndDosage">
                                <a-select class="yuan-form-input" v-model="formData.packagingForm" placeholder="请选择">
                                    <a-select-option value="袋装">袋装</a-select-option>
                                    <a-select-option value="盒装">盒装</a-select-option>
                                </a-select>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-item yuan-form-col3" label="物料代码" prop="materialCode">
                                <a-input class="yuan-form-input" v-model="formData.materialCode" placeholder="请输入"></a-input>
                            </a-form-model-item>
                            <div class="clear-both"></div>

                            <template v-if="formData.productType==='直服饮片' || formData.productType==='中药饮片' || formData.productType==='单方饮片'">
                                <a-form-model-item class="yuan-form-item yuan-form-col3" label="产品大类" prop="productBigKind">
                                    <a-select class="yuan-form-input" v-model="formData.productBigKind" placeholder="请选择" @change="getPackSpecification">
                                        <a-select-option v-for="(item,idx) in bigKindList" :key="'bigKind_'+idx" :value="item">{{item}}</a-select-option>
                                    </a-select>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-item yuan-form-col3" label="装量" prop="packSpecification">
                                    <a-select v-if="formData.productBigKind" class="yuan-form-input" v-model="formData.packSpecification" placeholder="请选择" @change="bigKindChange">
                                        <a-select-option v-for="(item,idx) in packSpecificationList" :key="'packSpecification_'+idx" :value="item">{{item}}</a-select-option>
                                    </a-select>
                                    <span v-else>请选择产品大类</span>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-item yuan-form-col3" label="色卡">
                                    <div v-if="formData.packSpecification" style="width: 90px;height: 30px" :style="{backgroundColor: formData.colorChart}"></div>
                                    <span v-else>请选择装量</span>
                                </a-form-model-item>
<!--                                <a-form-model-item class="yuan-form-item yuan-form-col3" label="存货代码" prop="inventoryCode">-->
<!--                                    <a-input class="yuan-form-input" v-model="formData.inventoryCode" placeholder="请输入"></a-input>-->
<!--                                </a-form-model-item>-->
                                <div class="clear-both"></div>
                                <a-form-model-item class="yuan-form-item yuan-form-col3" label="规格" prop="specification">
                                    <a-input class="yuan-form-input" v-model="formData.specification" placeholder="请输入"></a-input>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-item yuan-form-col3" label="贮藏" prop="stockpileCondition">
                                    <a-input class="yuan-form-input" v-model="formData.stockpileCondition"
                                        placeholder="请输入"></a-input>
                                </a-form-model-item>
                                <div class="clear-both"></div>
                                <a-form-model-item class="yuan-form-item yuan-form-col3" label="注意事项" prop="notes">
                                    <a-input class="yuan-form-input" v-model="formData.notes" placeholder="请输入"></a-input>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-item yuan-form-col3" label="用法与用量" prop="usageAndDosage">
                                    <a-input class="yuan-form-input" v-model="formData.usageAndDosage"
                                        placeholder="请输入"></a-input>
                                </a-form-model-item>
                                
                                <a-form-model-item class="yuan-form-item" label="功能与主治" prop="functionsOfCuring">
                                    <a-input type="textarea" style="width: 500px;" :rows="5" v-model="formData.functionsOfCuring"
                                        placeholder="请输入功能与主治" :maxLength="200" />
                                    <div class="textarea-number">
                                        {{ formData.functionsOfCuring ? formData.functionsOfCuring.length : 0 }}/200
                                    </div>
                                </a-form-model-item>

                            </template>

                            <a-form-model-item class="yuan-form-item" :label="'产地信息'" prop="selectAddr">
                                <a-button class="" type="primary" @click="addAddr">新增产地</a-button>
                            </a-form-model-item>
                            <div class="clear-both"></div>
                            <template v-for="(item,idx) in addrList">
                                <template v-if="item.time">
                                    <a-form-model-item class="yuan-form-item" :label="'产地'+(idx+1)" prop="placeAreaCode"
                                        :key="'addr_'+item.time">

                                        <a-input class="yuan-form-input" v-model="addrList[idx].words" placeholder="请输入产地" />

                                        <a-icon class="c-danger" type="delete" @click="removeAddr(idx)" style="margin-left:5px" />
                                    </a-form-model-item>
                                </template>
                                <template v-else>
                                    <a-form-model-item class="yuan-form-item" :label="'产地'+(idx+1)" prop="placeAreaCode"
                                        :key="'addr_'+idx+'_'+item.words">
                                        <span class="yuan-form-input">{{item.words}}</span>
                                        <a-icon class="c-danger" type="delete" @click="removeAddr(idx)" style="margin-left:5px" />
                                    </a-form-model-item>
                                </template>

                            </template>
                            <div class="clear-both" style="margin-bottom:10px"></div>

<!--                            <a-form-model-item class="yuan-form-item yuan-form-col3" label="发药机编码" prop="dispensingMachineCoder"-->
<!--                                v-if="formData.productType==='成品'">-->
<!--                                <a-input class="yuan-form-input" v-model="formData.dispensingMachineCoder"-->
<!--                                    placeholder="请输入"></a-input>-->
<!--                            </a-form-model-item>-->

                            <a-form-model-item class="yuan-form-item yuan-form-col3" label="保质期" prop="expirationDate">
                                <a-input class="yuan-form-input" type="number" suffix="月" v-model="formData.expirationDate"
                                    placeholder="请输入"></a-input>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-item" label="状态" prop="state">
                                <a-radio-group v-model="formData.state"
                                    :options="[{ 'label': '启用', value: 0 }, { 'label': '禁用', value: 1 }]" :default-value="0" />
                            </a-form-model-item>
                        </div>

                    </div>
                </a-form-model>
            </a-spin>
        </a-modal>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Watch, Vue } from "vue-property-decorator";
import nextApi from "@/api/nextApi";
import config from "@/utils/config";
import areaJson, { getAreaWords } from "@/utils/area";
@Component({
    name: "Add",
})
export default class extends Vue {
    @Prop({ default: false }) visible!: boolean;
    @Prop({ default: "" }) infoId!: string;
    @Prop({ default: "" }) rowKey!: string;
    @Watch("visible")
    visibleChange() {
        if (this.visible) {
            this.getDetail();
        }
        this.modalOption.title = this.infoId ? "编辑物料" : "新增物料";
    }

    addrData = areaJson;
    tabsData = config.tabsData;
    formLoading = false;
    modalOption = {
        title: "新增物料",
        okText: "保存",
        cancelText: "取消",
        onOk: () => {
            this.modalOk();
        },
        onCancel: () => {
            this.closeModal();
        },
    };
    rules = {
        varietyName: [{ required: true, message: "请输入品种名称", trigger: "blur" }],
        materialCode: [{ required: true, message: "请输入物料代码", trigger: "blur" }],
        selectAddr: [
            {
                required: false,
                message: "请选择产地",
                trigger: "change",
                validator: (rule: any, value: any, callback: any) => callback(),
            },
        ],
        state: [{ required: true, message: "请选择产地", trigger: "change" }],
        productBigKind: [{ required: true, message: "请选择产品大类", trigger: "blur" }],
        // inventoryCode: [{ required: true, message: "请选择存货代码", trigger: "blur" }],
        packSpecification: [{ required: true, message: "请选择装量", trigger: "blur" }],
        specification:[{required:true,message:'请填写规格',trigger:'blur'}],
        stockpileCondition:[{required:true,message:"请填写贮藏",trigger:'blur'}],
        expirationDate:[{required:true,message:'请填写保质期',trigger:'blur'}],
        medicineClass:[{required:true,message:'请选择中药等级',trigger:'blur'}],

    };
    formData: any = {};
    resetForm() {
        this.formData = {};
    }
    async mounted() {
        this.resetForm();
    }
    bigKindChange(){
        let arr = [
            { value: "1g", color: "#08062C" },
            { value: "3g", color: "#00312C" },
            { value: "5g", color: "#00355C" },
            { value: "6g", color: "#08201C" },
            { value: "9g", color: "#08321C" },
            { value: "10g", color: "#00299C" },
            { value: "12g", color: "#08021C" },
            { value: "15g", color: "#07474C" },
            { value: "30g", color: "#08100C" },
        ]
        //如果选择的规格中包含了arr中的值，就将formData的colorChart设置为arr中对应的值，否则就设置为白色
        this.formData.colorChart = (this.formData.packSpecification && arr.find((item) => this.formData.packSpecification.includes(item.value)))?.color || "#FFFFFF";
        console.log(this.formData)
    }
    closeModal() {
        this.resetForm();
        (this.$refs.form as any).resetFields();
        this.$emit("closeModal");
    }
    modalOk() {
        (this.$refs.form as any).validate(async (valid: any) => {
            console.info(valid);
            if (valid) {
                this.formLoading = true;
                try {
                    this.formData.id = this.infoId || "";
                    let placeOfOriginJSON = this.addrList.map((item) => item.words);
                    placeOfOriginJSON = placeOfOriginJSON.filter((item) => item !== "");
                    if (this.formData.productType == "中药材" && placeOfOriginJSON.length === 0) {
                        this.$message.error("请至少选择一个产地");
                        return;
                    }
                    this.formData.placeOfOriginJSON = placeOfOriginJSON;
                    const res = await nextApi.editMaterial(this.formData);
                    this.$message.success(res.msg);
                    this.closeModal();
                    this.$emit("resetList");
                } finally {
                    this.formLoading = false;
                }
            }
        });
    }
    //产品大类改变查询对应产品大类的装量
    packSpecificationList: any[] = [];
    async getPackSpecification(){
        const res = await nextApi.getProductVolumeList({productType:this.formData.productType,productBigKind:this.formData.productBigKind})
        this.packSpecificationList = res.data
        //只保留discretion字段并去重
        this.packSpecificationList = this.packSpecificationList.map((item)=>item.discretion).filter((item,index,self)=>self.indexOf(item)===index)
    }
    //查询产品大类
    bigKindList: any[] = [];
    async getProductVolume(){
        const res = await nextApi.getProductVolumeList({productType:this.formData.productType,medicineClass:this.formData.medicineClass})
        this.bigKindList = res.data
        //只保留productBigKind字段并去重
        this.bigKindList = this.bigKindList.map((item)=>item.productBigKind).filter((item,index,self)=>self.indexOf(item)===index)

    }
    //中药等级改变
    async medicineClassChange(){
        await this.getProductVolume()
    }
    async getDetail() {
        this.formLoading = true;
        this.addrList = [];
        await this.getSubject();
        try {
            if (this.infoId) {
                const res = await nextApi.getMaterialDetail({ id: this.infoId });
                this.formData = { ...res.data };
                if(res.data.placeOfOriginJSON){
                    this.addrList = res.data.placeOfOriginJSON.map((item) => ({ words: item }));
                    console.info(this.addrList);
                }
                await this.getProductVolume()
                await this.getPackSpecification()
            } else {
                this.formData = {
                    productType: this.rowKey,
                    source: "自培育",
                    state: 0,
                    medicineClass:"",
                    medicineValue:""
                };
                if(this.formData.productType !== "中药饮片"){
                    await this.getProductVolume()
                }
            }
        } finally {
            this.formLoading = false;
        }
    }
    /**
     * 获取科目信息
     */
    subjectList: any[] = [];
    async getSubject() {
        if (this.subjectList && this.subjectList.length > 0) return;
        const res = await nextApi.getSubjectList();
        this.subjectList = res.data;
    }
    subjectChange() {
        const find = this.subjectList.find((item) => item.id === this.formData.subjectId);
        if (find) {
            this.formData.subjectName = find.typename;
            this.formData.genericName = "";
            this.formData.basinymName = "";
            this.formData.basinymLatin = "";
            this.getCategoryList(find.id);
        }
    }

    categoryList: any[] = [];
    async getCategoryList(id: string) {
        this.formLoading = true;
        const res = await nextApi.getCategoryList(id);
        this.categoryList = res.data;
        this.formLoading = false;
    }
    categoryChange() {
        const find = this.categoryList[this.formData.categoryIdx];
        if (find) {
            this.formData.genericName = find;
            this.getSeedList(find);
        }
    }
    seedList: any[] = [];
    async getSeedList(name: string) {
        this.formLoading = true;
        const res = await nextApi.getSeedList(name);
        this.seedList = res.data;
        this.formLoading = false;
    }
    seedChange() {
        const find = this.seedList[this.formData.seedIdx];
        if (find) {
            this.formData.basinymName = find.seedName;
            this.formData.basinymLatin = find.seedLatin;
        }
    }
    addrList: any[] = [];
    onAddrChange(e: any, idx: number) {
        this.addrList[idx] = {
            placeAreaCode: e.join(";"),
            selectCode: e,
            words: getAreaWords(e),
            time: new Date().getTime(),
        };
    }
    addAddr() {
        this.addrList.push({ placeAreaCode: "", words: "", time: new Date().getTime() });
    }
    removeAddr(idx: number) {
        this.addrList.splice(idx, 1);
    }

    async varietyNameChange() {
        if (!this.formData.varietyName) return;
        this.formLoading = true;
        const res = await nextApi.getVarietyName({ varietyName: this.formData.varietyName });

        if (res.data && res.data.basinymName) {
            this.formData.subjectName = res.data.subjectName;
            this.formData.genericName = res.data.genericName;
            this.formData.basinymName = res.data.basinymName;
            this.formData.basinymLatin = res.data.basinymLatin;
        } else {
            this.formData.subjectName = "";
            this.formData.genericName = "";
            this.formData.basinymName = "";
            this.formData.basinymLatin = "";
        }

        this.formLoading = false;
    }
}
</script>
<style lang="scss">
.material-add-modal {
    .textarea-number {
        position: absolute;
        right: 10px;
        bottom: 2px;
        line-height: 20px;
        font-size: 12px;
    }
}
</style>
